﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Acms.AcmsControls.ContentControls.FrontEnd;
using Acms.Bll;


namespace Ait.Web.Templates.SearchPage
{
    public partial class _default : Acms.AcmsControls.TemplatePage
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            
            dsListItems.SelectData += new EventHandler<Acms.DataControls.SelectEventArgs<Search>>(dsList_SelectData);
        }
        
        void dsList_SelectData(object sender, Acms.DataControls.SelectEventArgs<Acms.Bll.Search> e)
        {
            if (!string.IsNullOrEmpty(SearchTerm))
            {
                int totalRecords = 0;
                List<Acms.Bll.Search> tmp = Acms.Bll.Search.GetAllBySearchTerm(AcmsContext.SiteId, SearchTerm, AcmsContext.SiteVersion, e.StartRowIndex, e.MaximumRecords, ref totalRecords);
                e.SetData(tmp, totalRecords);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["Term"] != null)
                {
                    SearchTerm = txtSearchTerm.Text = Request.QueryString["Term"];
                    accordian.SelectedIndex = 0;
                }
                else
                {
                    accordian.SelectedIndex = 0;
                    dlFeed.Visible = false;
                }
                DataBind();
            }
        }

        protected void btnSearchTerm_Click(object sender, EventArgs e)
        {
            if (IsValid)
            {
                accordian.SelectedIndex = 0;
                SearchTerm = txtSearchTerm.Text;
                DoSearch();
            }
        }

        private void DoSearch()
        {
            dlFeed.Visible = true;
            dlFeed.DataBind();
        }

        public override void DataBind()
        {
            if (!string.IsNullOrEmpty(SearchTerm))
            {
                DoSearch();
            }
            base.DataBind();
        }

        protected string SearchTerm { get; set; }

        protected string GetSearchTitle()
        {
            if (!string.IsNullOrEmpty(SearchTerm))
            {
                return string.Format("Search \"{0}\"", SearchTerm);
            }
            else
            {
                return "Search";
            }
        }

        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);
            SearchTerm = ViewState["SearchTerm"] as string;
        }

        protected override object SaveViewState()
        {
            ViewState["SearchTerm"] = SearchTerm;
            return base.SaveViewState();
        }
    }
}
